<template>
  <div class="rela" v-loading="loading">
    <!-- 吸顶-->
    <div
      class="ceiling shou"
      style="top: 0"
      v-if="srolledNum > 0"
      @click="scrollToTarget('card0')"
    >
      图片({{ files.img.length }})
    </div>
    <div
      class="ceiling shou"
      style="top: 40px"
      v-if="srolledNum > 1"
      @click="scrollToTarget('card1')"
    >
      视频({{ files.video.length }})
    </div>
    <div
      class="ceiling shou"
      style="top: 80px"
      v-if="srolledNum > 2"
      @click="scrollToTarget('card2')"
    >
      文件({{ files.file.length }})
    </div>
    <!-- 滚动盒子 -->
    <div
      v-if="files.img.length + files.video.length + files.file.length > 0"
      class="studyResult"
      ref="scrollContainer"
      @scroll="checkElementVisibility"
    >
      <el-collapse v-model="activeNames">
        <div class="item" ref="card0" v-if="files.img.length > 0">
          <el-collapse-item name="1">
            <template slot="title">
              <div class="flexBet item_template">
                <div class="flex item_title">
                  <div class="item_title_txt">图片({{ files.img.length }})</div>
                  <div
                    class="item_title_tip"
                    v-if="type != 'detail' && sets.img == 'drag'"
                  >
                    注:拖拽视频并点击右侧“保存”按钮调整排序
                  </div>
                  <div
                    class="item_title_tip"
                    v-if="type != 'detail' && sets.img == 'delete'"
                  >
                    注：选择文件并点击“确定移除”按钮可将视频移除学生优秀成果。
                  </div>
                </div>
                <!-- 按钮组 -->
                <div class="flex item_btns">
                  <!-- 拖拽 -->
                  <img
                    v-if="sets.img == 'normal' && type != 'detail'"
                    @click.stop="handleDrag('img')"
                    class="item_btn"
                    src="@/assets/images/studyResults/tuozhuai.png"
                    alt="加载失败"
                  />
                  <!-- 删除 -->
                  <img
                    v-if="sets.img == 'normal' && type != 'detail'"
                    @click.stop="handleDelete('img')"
                    class="item_btn"
                    src="@/assets/images/studyResults/delete.png"
                    alt="加载失败"
                  />
                  <el-button
                    style="margin-top: 2px"
                    v-if="
                      (sets.img == 'drag' || sets.img == 'delete') &&
                      type != 'detail'
                    "
                    v-preventReClick
                    size="mini"
                    @click.stop="handleCancel('img')"
                    >取 消
                  </el-button>
                  <el-button
                    style="margin-top: 2px"
                    v-if="sets.img == 'drag' && type != 'detail'"
                    v-preventReClick
                    size="mini"
                    type="primary"
                    @click.stop="handleSave('img')"
                    >保 存
                  </el-button>
                  <el-button
                    style="margin-top: 2px"
                    v-if="sets.img == 'delete' && type != 'detail'"
                    v-preventReClick
                    size="mini"
                    type="primary"
                    @click.stop="handleDeleteSubmit('img')"
                    >确定移除
                  </el-button>
                  <img
                    class="item_arrow"
                    src="@/assets/images/studyResults/arrow.png"
                    alt="加载失败"
                  />
                </div>
              </div>
            </template>
            <!-- 文件盒子 -->
            <vuedraggable
              class="filesBox flex"
              :disabled="sets.img != 'drag'"
              v-model="files.img"
            >
              <div
                @click="fileClick(item, index, 'img')"
                class="file_item flexCen flexcolenter rela shou"
                v-for="(item, index) in files.img"
                :key="index"
              >
                <!-- 选中 -->
                <div
                  @click.stop=""
                  class="file_item_checkbox shou absolute"
                  v-if="sets.img == 'delete'"
                >
                  <el-checkbox v-model="item.selected"> </el-checkbox>
                </div>
                <img v-if="item.type == 1" :src="item.url" alt="加载失败" />
                <video
                  v-else-if="item.type == 2"
                  :src="item.url"
                  controls
                ></video>
                <div class="file" v-else>
                  <img :src="returnIcon(item.url, 1)" alt="加载失败" class="icon" />
                  <tooltip
                    width="140"
                    class="filename"
                    :text="item.file_name"
                  ></tooltip>
                </div>
              </div>
            </vuedraggable>
          </el-collapse-item>
        </div>
        <div class="item" ref="card1" v-if="files.video.length > 0">
          <el-collapse-item name="2">
            <template slot="title">
              <div class="flexBet item_template">
                <div class="flex item_title">
                  <div class="item_title_txt">
                    视频({{ files.video.length }})
                  </div>
                  <div
                    class="item_title_tip"
                    v-if="type != 'detail' && sets.video == 'drag'"
                  >
                    注:拖拽视频并点击右侧“保存”按钮调整排序
                  </div>
                  <div
                    class="item_title_tip"
                    v-if="type != 'detail' && sets.video == 'delete'"
                  >
                    注：选择文件并点击“确定移除”按钮可将视频移除学生优秀成果。
                  </div>
                </div>
                <!-- 按钮组 -->
                <div class="flex item_btns">
                  <!-- 拖拽 -->
                  <img
                    v-if="sets.video == 'normal' && type != 'detail'"
                    @click.stop="handleDrag('video')"
                    class="item_btn"
                    src="@/assets/images/studyResults/tuozhuai.png"
                    alt="加载失败"
                  />
                  <!-- 删除 -->
                  <img
                    v-if="sets.video == 'normal' && type != 'detail'"
                    @click.stop="handleDelete('video')"
                    class="item_btn"
                    src="@/assets/images/studyResults/delete.png"
                    alt="加载失败"
                  />
                  <el-button
                    style="margin-top: 2px"
                    v-if="
                      (sets.video == 'drag' || sets.video == 'delete') &&
                      type != 'detail'
                    "
                    v-preventReClick
                    size="mini"
                    @click.stop="handleCancel('video')"
                    >取 消
                  </el-button>
                  <el-button
                    style="margin-top: 2px"
                    v-if="sets.video == 'drag' && type != 'detail'"
                    v-preventReClick
                    size="mini"
                    type="primary"
                    @click.stop="handleSave('video')"
                    >保 存
                  </el-button>
                  <el-button
                    style="margin-top: 2px"
                    v-if="sets.video == 'delete' && type != 'detail'"
                    v-preventReClick
                    size="mini"
                    type="primary"
                    @click.stop="handleDeleteSubmit('video')"
                    >确定移除
                  </el-button>
                  <img
                    class="item_arrow"
                    src="@/assets/images/studyResults/arrow.png"
                    alt="加载失败"
                  />
                </div>
              </div>
            </template>
            <!-- 文件盒子 -->
            <vuedraggable
              class="filesBox flex"
              :disabled="sets.video != 'drag'"
              v-model="files.video"
            >
              <div
                @click="fileClick(item, index, 'video')"
                class="file_item flexCen flexcolenter rela shou"
                v-for="(item, index) in files.video"
                :key="index"
              >
                <!-- 选中 -->
                <div
                  @click.stop=""
                  class="file_item_checkbox shou absolute"
                  v-if="sets.video == 'delete'"
                >
                  <el-checkbox v-model="item.selected"> </el-checkbox>
                </div>
                <img v-if="item.type == 1" :src="item.url" alt="加载失败" />
                <video
                  v-else-if="item.type == 2"
                  :src="item.url"
                  controls
                ></video>
                <div class="file" v-else>
                  <img :src="returnIcon(item.url, 1)" alt="加载失败" class="icon" />
                  <tooltip
                    width="140"
                    class="filename"
                    :text="item.file_name"
                  ></tooltip>
                </div>
              </div>
            </vuedraggable>
          </el-collapse-item>
        </div>
        <div class="item" ref="card2" v-if="files.file.length > 0">
          <el-collapse-item name="3">
            <template slot="title">
              <div class="flexBet item_template">
                <div class="flex item_title">
                  <div class="item_title_txt">
                    文件({{ files.file.length }})
                  </div>
                  <div
                    class="item_title_tip"
                    v-if="type != 'detail' && sets.file == 'drag'"
                  >
                    注:拖拽视频并点击右侧“保存”按钮调整排序
                  </div>
                  <div
                    class="item_title_tip"
                    v-if="type != 'detail' && sets.file == 'delete'"
                  >
                    注：选择文件并点击“确定移除”按钮可将视频移除学生优秀成果。
                  </div>
                </div>
                <!-- 按钮组 -->
                <div class="flex item_btns">
                  <!-- 拖拽 -->
                  <img
                    v-if="sets.file == 'normal' && type != 'detail'"
                    @click.stop="handleDrag('file')"
                    class="item_btn"
                    src="@/assets/images/studyResults/tuozhuai.png"
                    alt="加载失败"
                  />
                  <!-- 删除 -->
                  <img
                    v-if="sets.file == 'normal' && type != 'detail'"
                    @click.stop="handleDelete('file')"
                    class="item_btn"
                    src="@/assets/images/studyResults/delete.png"
                    alt="加载失败"
                  />
                  <el-button
                    style="margin-top: 2px"
                    v-if="
                      (sets.file == 'drag' || sets.file == 'delete') &&
                      type != 'detail'
                    "
                    v-preventReClick
                    size="mini"
                    @click.stop="handleCancel('file')"
                    >取 消
                  </el-button>
                  <el-button
                    style="margin-top: 2px"
                    v-if="sets.file == 'drag' && type != 'detail'"
                    v-preventReClick
                    size="mini"
                    type="primary"
                    @click.stop="handleSave('file')"
                    >保 存
                  </el-button>
                  <el-button
                    style="margin-top: 2px"
                    v-if="sets.file == 'delete' && type != 'detail'"
                    v-preventReClick
                    size="mini"
                    type="primary"
                    @click.stop="handleDeleteSubmit('file')"
                    >确定移除
                  </el-button>
                  <img
                    class="item_arrow"
                    src="@/assets/images/studyResults/arrow.png"
                    alt="加载失败"
                  />
                </div>
              </div>
            </template>
            <!-- 文件盒子 -->
            <vuedraggable
              class="filesBox flex"
              :disabled="sets.file != 'drag'"
              v-model="files.file"
            >
              <div
                @click="fileClick(item, index, 'file')"
                class="file_item flexCen flexcolenter rela shou"
                v-for="(item, index) in files.file"
                :key="index"
              >
                <!-- 选中 -->
                <div
                  @click.stop=""
                  class="file_item_checkbox shou absolute"
                  v-if="sets.file == 'delete'"
                >
                  <el-checkbox v-model="item.selected"> </el-checkbox>
                </div>
                <img v-if="item.type == 1" :src="item.url" alt="加载失败" />
                <video
                  v-else-if="item.type == 2"
                  :src="item.url"
                  controls
                ></video>
                <div class="file" v-else>
                  <img :src="returnIcon(item.url, 1)" alt="加载失败" class="icon" />
                  <tooltip
                    width="140"
                    class="filename"
                    :text="item.file_name"
                  ></tooltip>
                </div>
              </div>
            </vuedraggable>
          </el-collapse-item>
        </div>
      </el-collapse>
    </div>
    <div class="studyResult" v-else>
      <el-empty description="暂无学生优秀成果"></el-empty>
    </div>

    <div class="studyResultbottom flexEnd">
      <el-button
        v-preventReClick
        type="primary"
        v-if="type == 'edit'"
        @click="goBack"
        >退 出
      </el-button>
    </div>
    <!-- 预览 -->
    <fileDrawer
      :preview="preview"
      :show.sync="drawer"
      :url="drawerurl"
      :name="drawername"
      :paramsIndex="drawerIndex"
      :type="1"
    ></fileDrawer>
  </div>
</template>

<script>
import { returnIcon, isVideo, isImage } from "@/utils/util.js";
import {
  excellentLearningResult,
  deleteExcellentLearningResult,
  learningResultSort,
} from "@/api/studyResult/studyResult";
import vuedraggable from "vuedraggable";
export default {
  components: { vuedraggable },
  props: {
    type: [String],
    //判断任务还是目录   1  任务    2  目录
    selectedType: [String, Number],
    //课程信息
    courseForm: [Object],
    selectedTaskId: [String, Number],
    //判断当前选中的  tabs
    tabIndex: [String, Number],
    // preview
    preview: {
      type: Object,
      default: {},
      require: false,
    },
  },
  data() {
    return {
      drawer: false,
      drawerurl: "",
      drawerIndex: "",
      drawername: "",
      returnIcon: function (url, type) {
        return returnIcon(url, type);
      },
      isVideo: function (url) {
        return isVideo(url);
      },
      isImage: function (url) {
        return isImage(url);
      },
      loading: false,
      form: {
        id: "",
      },
      // 已滚动过去的数量
      srolledNum: -1,
      // 手风琴展开数组
      activeNames: ["1", "2", "3"],
      // 当前是否为编辑模式 drag delete normal
      sets: {
        img: "normal",
        video: "normal",
        file: "normal",
      },
      // 文件列表
      files: {
        img: [],
        video: [],
        file: [],
      },
      oldFiles: {
        img: [],
        video: [],
        file: [],
      },
      vuedraggable_disabled: false,
    };
  },
  mounted() {},
  created() {},
  beforeDestroy() {
    console.log("beforeDestroy", this.type, this.tabIndex, this.form.id);
    if (
      (this.type == "add" || this.type == "edit") &&
      this.tabIndex == 4 &&
      this.form.id
    ) {
      this.submitForm();
    }
  },
  watch: {
    //监听form.id   来判断同组件切换时   保存上一个内容
    form: {
      handler(newValue, oldValue) {
        console.log("addStudyResults监听form.id", oldValue.id, newValue.id);
        //判断有旧的form.id   说明是同组件切换   没有则证明是初次加载该组件
        //判断有旧的form.id  是否变化   有变化说明是组件切换了数据  将旧的id数据保存
        //deleteId>>>>>>>>>>删除过的 树节点id  如果oldValue.id==deleteId 说明oldValue节点已经被删除了，所以不用保存oldValue数据
        if (oldValue.id != newValue.id && oldValue.id && this.tabIndex == 4) {
          this.submitForm(oldValue);
        }
      },
      deep: true,
    },

    preview: {
      handler(newValue, oldValue) {
        // 这里来获取preview
        this.preview = newValue ? newValue : {};
        console.log('addStudyResults监听preview',this.preview);
      },
      deep: true,
    },
    selectedTaskId: {
      handler(newValue, oldValue) {
        console.log("selectedTaskId", newValue, oldValue)
        if(this.tabIndex == 4){
          // 每次更换组件 获取学生优秀成果
          this.excellentLearningResult();
        }
      },
    },
  },
  methods: {
    formatterTime(isoTime) {
      let date = new Date(isoTime);

      // 格式化日期和时间
      let year = date.getFullYear();
      let month = ("0" + (date.getMonth() + 1)).slice(-2); // getMonth()返回0-11，所以需要+1
      let day = ("0" + date.getDate()).slice(-2);
      let hours = ("0" + date.getHours()).slice(-2);
      let minutes = ("0" + date.getMinutes()).slice(-2);
      let seconds = ("0" + date.getSeconds()).slice(-2);

      let formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      return formattedTime;
    },
    /* 获取学生优秀成果 */
    async excellentLearningResult(refresh) {
      this.loading = true;
      this.files = {
        img: [],
        video: [],
        file: [],
      };
      let res;
      try {
        res = await excellentLearningResult(this.selectedTaskId);

        if (res.code == 200) {
          console.log(res.data);
          res.data.map((item) => {
            item.selected = false;
            item.createTime = this.formatterTime(item.create_time);
            if (this.isImage(item.url)) {
              item.type = 1;
              this.files.img.push(item);
            } else if (this.isVideo(item.url)) {
              item.type = 2;
              this.files.video.push(item);
            } else {
              item.type = 3;
              this.files.file.push(item);
            }
          });
          console.log('恢复默认模式',this.files);
          // 恢复默认模式 且全部展开
          this.sets = {
            img: "normal",
            video: "normal",
            file: "normal",
          };
          this.activeNames = ["1", "2", "3"];
        }
      } finally {
        this.loading = false;
      }
    },
    // 用于删除的时候(选中)
    fileClick(item, index, type) {
      if (this.sets[type] == "delete") {
        item.selected = !item.selected;
      } else {
        console.log("预览",this.files);
        this.drawer = true;
        this.drawerurl = this.files[type];
        this.drawerIndex = index;
      }
    },

    // 开始刪除按鈕
    handleDelete(type) {
      this.files[type].map((item) => {
        item.selected = false;
      });
      this.sets[type] = "delete";
    },
    // 确定移除按钮
    async handleDeleteSubmit(type) {
      let deletes = this.files[type]
        .filter((item) => {
          return item.selected;
        })
        .map((item) => {
          return item.id;
        });
      if (deletes.length == 0) {
        this.$message({
          message: "请选择要移除的优秀成果",
          type: "warning",
        });
        return false;
      }
      let res;
      try {
        this.loading = true;
        res = await deleteExcellentLearningResult(deletes.join(","));
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "删除成功",
          });
          this.files[type] = this.files[type].filter(
            (item) => !deletes.includes(item.id)
          );
          this.sets[type] = "normal";
          this.$forceUpdate();
          console.log(this.files);
        }
      } finally {
        this.loading = false;
      }
    },
    // 开始拖拽按钮
    handleDrag(type) {
      this.sets[type] = "drag";
      this.oldFiles = { ...this.files };
    },
    // 保存拖拽按鈕
    async handleSave(type) {
      let file = { ...this.files };
      let oldFiles = { ...this.oldFiles };
      let data = [];
      for (let key in oldFiles) {
        if (oldFiles.hasOwnProperty(key)) {
          // 如果拖拽的是当前的 则操作新数组
          if (key == type) {
            oldFiles[key] = file[type].map((item) => {
              return item.id;
            });
            console.log(key, oldFiles[key]);
          }
          // 其他的则是拿 老的排列顺序拼接（比如图片是正在拖拽 则需要拼接上没拖拽过的 视频和文件）
          else {
            oldFiles[key] = oldFiles[key].map((item) => {
              return item.id;
            });
            console.log(key, oldFiles[key]);
          }

          data = [...data, ...oldFiles[key]];
        }
      }
      console.log(data);
      let res;
      try {
        this.loading = true;
        res = await learningResultSort(data.join(","));
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "排序成功",
          });
          this.sets[type] = "normal";
        }
      } finally {
        this.loading = false;
      }
    },
    // 取消按鈕
    handleCancel(type) {
      if (this.sets[type] == "drag") {
        this.files[type] = JSON.parse(JSON.stringify(this.oldFiles[type]));
      }
      this.sets[type] = "normal";
    },
    scrollToTarget(e) {
      // 使用scrollIntoView平滑滚动到目标元素
      this.$refs[e].scrollIntoView({ behavior: "smooth" });
    },
    checkElementVisibility() {
      // 获取滚动容器当前的滚动位置
      const scrollTop = this.$refs.scrollContainer.scrollTop;
      let srolledNum = 0;
      for (let i = 0; i < 3; i++) {
        // 获取imgs元素的顶部位置
        const imgsTop = this.$refs[`card${i}`].offsetTop;
        // 获取imgs元素的高度，用于精确判断是否完全滚动过去
        const imgsHeight = this.$refs[`card${i}`].offsetHeight;
        // 判断imgs元素是否已经完全滚动出可视范围
        const isScrolledPast = scrollTop - imgsTop + 35 >= imgsHeight;
        if (i == 0) {
          console.log(scrollTop - imgsTop + 35, imgsHeight);
        }

        if (isScrolledPast) {
          srolledNum++;
        }
      }
      this.srolledNum = srolledNum;
    },
    submitForm(oldValue) {
      console.log(
        this.files
          .map((item) => {
            return item.id;
          })
          .join(",")
      );
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    goBack() {
      this.$router.go(-1);
    },
  },
};
</script>
<style scoped lang="scss">
.ceiling {
  z-index: 10;
  width: 100%;
  left: 0;
  border-bottom: 1px solid #eeeeee;
  position: absolute;
  height: 40px;
  line-height: 40px;
  box-sizing: border-box;
  padding: 0 10px;
  font-size: 16px;
  font-weight: 500;
  color: rgba(51, 51, 51, 1);
  background: white;
}
.studyResultbottom {
  border-top: 1px solid #ebebeb;
  height: 72px;
  box-sizing: border-box;
  padding: 0 19px 0 37px;
  align-items: center;

  ::v-deep .el-button {
    padding: 0 24px;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC, sans-serif;
    font-weight: 400;
    border-radius: 8px;
    line-height: 38px;
    height: 40px;
  }
}

.studyResult {
  box-sizing: border-box;
  padding: 10px 25px;

  box-sizing: border-box;
  height: calc(100vh - 310px + 77px - 72px);
  overflow: auto;
  .item {
    user-select: none;
    padding-bottom: 10px;
    .item_template {
      height: 38px;
      width: 100%;
    }

    .item_title {
      .item_title_txt {
        font-size: 16px;
        font-weight: 500;
        color: rgba(51, 51, 51, 1);
      }
      .item_title_tip {
        margin: 3px 0 0 10px;
        font-size: 12px;
        font-weight: 400;
        color: rgba(255, 141, 26, 1);
      }
    }
    .item_btns {
      .item_btn {
        margin-top: 11px;
        margin-left: 12px;
        width: 16px;
        height: 16px;
      }
      .item_arrow {
        margin-top: 15px;
        margin-left: 30px;
        width: 14px;
        height: 8px;
        transition: all 0.5s ease;
      }
      ::v-deep .el-button--mini {
        padding: 7px 0;
        width: 60px;
        height: 30px;
        border-radius: 12px;
      }
    }
    ::v-deep .el-collapse-item__header {
      .item_arrow {
        transform: rotate(-90deg);
      }
    }
    ::v-deep .el-collapse-item__header.is-active {
      .item_arrow {
        transform: rotate(0);
      }
    }
    .filesBox {
      padding: 0 0 2px 0;
      .file_item:nth-of-type(5n + 1) {
        margin: 18px 0 0 2px;
      }
      .file_item {
        margin: 18px 0 0 18px;
        width: 150px;
        height: 110px;
        background: rgba(255, 255, 255, 1);
        box-shadow: 0 2px 8px rgba(99, 99, 99, 0.2);
        .file {
          width: 100%;
          height: 100%;
          .icon {
            margin: 20px 0 0 50px;
            width: 50px;
            height: auto;
          }
          .filename {
            text-align: center;
            margin: 0 0 0 10px;
          }
        }
        .file_item_checkbox {
          top: 5px;
          right: 9px;
        }
        img {
          max-width: 100%;
          max-height: 100%;
          object-fit: contain; /* 保持图片原始宽高比，并缩放至最大能适应容器的大小 */
          margin: auto; /* 图片居中 */
        }
        video {
          width: 100%;
          height: 100%;
        }
      }
      .file_item_checkbox {
        top: 5px;
        right: 9px;
      }
    }
  }
}
</style>
